﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZ;
using DAL;

namespace SinhNhat
{
    public partial class Cart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitData();
                
                LoadData();
            }
        }

        private void InitData()
        {
            List<PAYMENT> listPayment = new PaymentBIZ().GetAll();
            ddlPayment.DataSource = listPayment;
            ddlPayment.DataTextField = "Name";
            ddlPayment.DataValueField = "PaymentID";
            ddlPayment.DataBind();
        }

        private void ChangeDiv(bool status)
        {
            cartDiv.Visible = status;
            nocartDiv.Visible = !status;
        }

        private void LoadData()
        {
            if (Session[SinhNhat.Properties.Resources.CookieName] == null)
            {
                ChangeDiv(false);
                return;
            }

            Dictionary<string, CartObject> listCart = (Dictionary<string, CartObject>)Session[SinhNhat.Properties.Resources.CookieName];
            if (listCart == null || listCart.Count == 0)
            {
                ChangeDiv(false);
                return;
            }

            List<CartObject> list = new List<CartObject>();
            ProductBIZ productBIZ = new ProductBIZ();
            PRODUCT product = null;
            CartObject cart = null;
            decimal amount = 0;

            foreach (var item in listCart.Values)
            {
                product = productBIZ.GetByID(item.Product.ProductID);
                cart = new CartObject(product, item.Quantity);
                amount += product.Price.Value * item.Quantity;

                list.Add(cart);
            }

            grCart.DataSource = list;
            grCart.DataBind();

            //var amount = from o in list select o.Product.Price;
            lblSum.Text = amount.ToString("N0") + SinhNhat.Properties.Resources.current;

            ChangeDiv(true);
            up.Update();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            grCart.RowCommand += new GridViewCommandEventHandler(grCart_RowCommand);
            btnSave.Click += new EventHandler(btnSave_Click);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Order order = new Order();
            order.OrderID = Guid.NewGuid();
            order.CustomerName = txtName.Text;
            order.CustomerEmail = txtEmail.Text;
            order.CustomerAddress = txtAddress.Text;
            order.CustomerPhone = txtPhone.Text;
            order.Note = txtNote.Text;
            order.CreateDate = DateTime.Now;
            order.Amount = 0;

            order.PaymentID = WebUtils.ToGuid(ddlPayment.Value);
            order.BankName = txtBankName.Text;
            order.BankNumber = txtBankNumber.Text;
            order.Status = false;

            Dictionary<string, CartObject> listCart = (Dictionary<string, CartObject>)Session[SinhNhat.Properties.Resources.CookieName];
            ORDERDETAIL orderDetail = null;
            PRODUCT product = null;
            ProductBIZ productBIZ = new ProductBIZ();
            string strProductName = string.Empty; ;

            foreach (var item in listCart.Values)
            {
                orderDetail = new ORDERDETAIL();
                orderDetail.OrderID = order.OrderID;
                orderDetail.OrderDetailID = Guid.NewGuid();
                orderDetail.ProductID = item.Product.ProductID;

                product = productBIZ.GetByID(item.Product.ProductID);
                orderDetail.Price = product.Price;
                strProductName += product.Name + "<br/>";
                order.Amount += orderDetail.Price * item.Quantity;
                orderDetail.Quantity = item.Quantity;

                order.ORDERDETAILs.Add(orderDetail);
            }
            
            OrderBIZ orderBIZ = new OrderBIZ();
            orderBIZ.Add(order);
            
            //send email
            ParameterBIZ parameterBIZ = new ParameterBIZ();
            string from = parameterBIZ.GetByID(new Guid("C6360368-1BFF-4D41-93AE-48816B0FB179")).Value;
            string password = parameterBIZ.GetByID(new Guid("1754B1C3-404E-4B8C-87C8-5DFE4642BC02")).Value;
            string to = parameterBIZ.GetByID(new Guid("D9D71946-0265-45BC-A5A5-E2DDB5FDA3AE")).Value;

            string paymentName = new PaymentBIZ().GetByID(order.PaymentID.Value).Name;
            string linkWeb = "http://" + Request.Url.Authority + "/admin/EditOrder.aspx?orderID=" + order.OrderID;
            string title = "Đơn đặt hàng cuả " + order.CustomerName;
            string body = string.Format("<h2>Thông tin khách hàng:</h2>Tên khách hàng:{0}<br/>Email:{1}<br/>Điện thoại:{2}<br/>Địa chỉ:{3}<br/>Ghi chú:{4}<br/>Hình thức thanh toán:{5}<h2>Thông tin sản phẩm:</h2>{6}<br/><br/><br/>Xem chi tiết tại: {7}", 
                order.CustomerName, order.CustomerEmail, order.CustomerPhone, order.CustomerAddress, order.Note, paymentName, strProductName, linkWeb);
            WebUtils.sendMail(from, password, to, title, body);

            //clear session
            Session.Remove(SinhNhat.Properties.Resources.CookieName);

            //message
            cartDiv.Visible = nocartDiv.Visible = false;
            successDiv.Visible = true;
            up.Update();
        }

        public void grCart_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandArgument.Equals("Up"))
            {
                string productID = e.CommandName;
                Dictionary<string, CartObject> listCart = (Dictionary<string, CartObject>)Session[SinhNhat.Properties.Resources.CookieName];
                listCart[productID].Quantity += 1;

                LoadData();
            }
            else if (e.CommandArgument.Equals("Down"))
            {
                string productID = e.CommandName;
                Dictionary<string, CartObject> listCart = (Dictionary<string, CartObject>)Session[SinhNhat.Properties.Resources.CookieName];
                listCart[productID].Quantity -= 1;

                if (listCart[productID].Quantity == 0)
                {
                    listCart.Remove(productID);
                }

                LoadData();
            }
            else if (e.CommandArgument.Equals("Del"))
            {
                string productID = e.CommandName;
                Dictionary<string, CartObject> listCart = (Dictionary<string, CartObject>)Session[SinhNhat.Properties.Resources.CookieName];
                listCart.Remove(productID);

                LoadData();
            }
        }
    }
}